package com.fq.rpc.task;

import com.fq.rpc.domain.InterfaceWrapper;
import com.fq.rpc.util.Hessian2Serializer;
import com.fq.rpc.util.ReaderUtil;

import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.net.Socket;

/**
 * @author jifang
 * @since 16/8/4 上午11:26.
 */
public class ConsumerIInvokeTask implements InvocationHandler {

    private Class<?> inter;

    private String ip;

    private int port;

    public ConsumerIInvokeTask(Class<?> inter, String ip, int port) {
        this.inter = inter;
        this.ip = ip;
        this.port = port;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        Socket client = new Socket(ip, port);

        try (
                OutputStream out = client.getOutputStream();
                InputStream in = client.getInputStream()
        ) {
            // 序列化 写入数据
            InterfaceWrapper wrapper = new InterfaceWrapper();
            wrapper.setInter(this.inter);
            wrapper.setMethodName(method.getName());
            wrapper.setParamTypes(method.getParameterTypes());
            wrapper.setArguments(args);

            byte[] bytes = Hessian2Serializer.serialize(wrapper);
            out.write(bytes);

            // 读出数据 反序列化
            bytes = ReaderUtil.toByteArray(in);
            return Hessian2Serializer.deserialize(bytes);
        }
    }
}
